package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tanhua.common.service.VoiceUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.VoiceUploadResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Voice;
import com.tanhua.server.vo.VoiceVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

@Service
public class PeachBlossomService {

    private static final String LAST_VOICE_REDISKEY = "LATS_VOICE_";

    private static final String VOICE_LIST_REDISKEY = "VOICE_LIST_";

    @Autowired
    private VoiceUploadService voiceUploadService;

    @DubboReference(version = "1.0.0")
    private VoiceApi voiceApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;


    public Object sendVoice(MultipartFile soundFile) {

        Long userId = UserThreadLocal.get();

        VoiceUploadResult uploadResult = this.voiceUploadService.upload(soundFile);

        if (StrUtil.isEmpty(uploadResult.getName())) {
            return ErrorResult.builder().errCode("500")
                    .errMessage("语音发送失败，请重新重试！").build();
        }

        Boolean result = this.voiceApi.save(userId, uploadResult.getName());

        if (result) {
            return null;
        }

        return ErrorResult.builder().errCode("500")
                .errMessage("语音发送失败，请重新重试！").build();
    }

    public Object receiveVoice() {
        Long userId = UserThreadLocal.get();

        Long remainTimes = this.voiceApi.queryRemainTimes(userId);

        if (remainTimes < 0) {
            // 当日接受次数超过10次 可以记录最后一次用户信息
            String json = this.redisTemplate.opsForValue().get(LAST_VOICE_REDISKEY + userId);
            return JSONUtil.toBean(json, VoiceVo.class);
        }

        VoiceVo voiceVo = new VoiceVo();
        List<Voice> voiceList = this.voiceApi.queryRandomVoice(userId);
        if (CollUtil.isEmpty(voiceList)) {
            // 使用默认语音队列
            voiceList = this.voiceApi.queryDefaultVoice(userId);
            if(CollUtil.isEmpty(voiceList)){
                return ErrorResult.builder()
                        .errCode("500").errMessage("没有语音可以接受 goodbye！").build();
            }
        }

        // 随机获取一个语音
        Collections.shuffle(voiceList);
        Voice voice = voiceList.get(0);

        // 记录每次接受的语音ID
        this.redisTemplate.opsForHash().put(VOICE_LIST_REDISKEY + userId, voice.getId().toString(), "1");

        UserInfo userInfo = this.userInfoApi.queryByUserId(voice.getUserId());
        BeanUtil.copyProperties(userInfo, voiceVo, "id");
        voiceVo.setGender(userInfo.getSex().name().toLowerCase());
        voiceVo.setSoundUrl(voice.getSoundUrl());
        voiceVo.setRemainingTimes(Convert.toInt(remainTimes));

        if (voiceVo.getRemainingTimes() == 0) {
            String voiceJson = JSONUtil.toJsonStr(voiceVo);
            this.redisTemplate.opsForValue().set(LAST_VOICE_REDISKEY + userId, voiceJson);
        }
        return voiceVo;
    }

}
